package io.renren.modules.app.controller;

import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.modules.app.form.AttachmentListForm;
import io.renren.modules.oss.cloud.OSSFactory;
import io.renren.modules.oss.entity.SysOssEntity;
import io.renren.modules.oss.service.SysOssService;
import io.renren.modules.quickService.entity.AttachmentEntity;
import io.renren.modules.quickService.service.AttachmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 文件上传
 *
 * @author zenger380
 * @email zenger380@163.com
 * @date 2018-10-22 17:09:26
 */
@RestController
@RequestMapping("app/file")
@Api(value="APP附件上传管理",tags={"APP文件上传接口"})
public class AppUploadController {
    @Autowired
    private SysOssService sysOssService;
    @Autowired
    private AttachmentService attachmentService;
    /**
     * 文件上传
     */
    @PostMapping("/upload")
    @ApiOperation("注册")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("文件上传不能为空");
        }
        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);
        //保存文件信息
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setUrl(url);
        ossEntity.setCreateDate(new Date());
        sysOssService.insert(ossEntity);
        return R.ok().put("url", url);
    }
    /**
     * 附件列表保存
     */
    @PostMapping("/saveAttachments")
    @ApiOperation("订单附件列表保存")

    public R saveAttachmentList(@RequestBody  AttachmentListForm attachmentList){
        boolean flag =  attachmentService.saveAttachments(attachmentList.getAttachmentList(),attachmentList.getBizId(),attachmentList.getAttachmentType());
        if(!flag){
            return  R.error("附件列表保存失败");
        }
        return R.ok();
    }


    /**
     * 附件列表查询
     */
    @PostMapping("/attachments")
    @ApiOperation("订单附件列表查询")
    public R attachmentList(@RequestBody @ApiParam("{bizId:业务ID,attachmentType:附件类型}") Map<String, String> params){
        List<AttachmentEntity> attachmentList =  attachmentService.attachmentList(params.get("bizId"),params.get("attachmentType"));
        return R.ok().put("attachmentList",attachmentList);
    }


}
